<script setup>
import DlgResourceCreateOrEdit from './DlgResourceCreateOrEdit.vue';
import { ref, reactive, watch } from 'vue';
import { timeFormatter } from '@/utils/timeHandlers';
import { queriedResult, queryCondition, queryResources } from '@/composables/useResources';
import { allResourceCategory, getAllResourceCategory } from '@/composables/useResourceCategory';
import { deleteResource } from '@/api/resources';
import { useRouter } from 'vue-router';

const router = useRouter();

const queryFm = ref();

// 初始化查询
queryResources();
getAllResourceCategory();

const dlgCreateOrEdit = ref();  //对话框组件引用
const formInline = reactive({ ...queryCondition });

// 重置方法
const resetForm = () => {
  if (queryFm.value) {
    queryFm.value.resetFields();
    
    // 重置查询条件
    queryCondition.name = '';
    queryCondition.url = '';
    queryCondition.categoryId = '';
    queryCondition.current = 1; // 重置为第一页
    
    // 同步 formInline
    Object.assign(formInline, queryCondition);
    
    // 触发查询
    queryResources({
      current: queryCondition.current,
      size: queryCondition.size,
      name: queryCondition.name,
      url: queryCondition.url,
      categoryId: queryCondition.categoryId
    });
  }
};

// 查询资源
const handleQuery = () => {
  // 同步查询条件
  Object.assign(queryCondition, formInline);
  queryCondition.current = 1; // 重置为第一页
  
  // 触发查询
  queryResources({
    current: queryCondition.current,
    size: queryCondition.size,
    name: queryCondition.name,
    url: queryCondition.url,
    categoryId: queryCondition.categoryId
  });
};

// 页码变化时更新查询
const handleCurrentChange = (current) => {
  queryCondition.current = current;
  
  // 触发查询
  queryResources({
    current: queryCondition.current,
    size: queryCondition.size,
    name: queryCondition.name,
    url: queryCondition.url,
    categoryId: queryCondition.categoryId
  });
};

// 每页数量变化时更新查询
const handleSizeChange = (size) => {
  queryCondition.size = size;
  queryCondition.current = 1; // 重置为第一页
  
  // 触发查询
  queryResources({
    current: queryCondition.current,
    size: queryCondition.size,
    name: queryCondition.name,
    url: queryCondition.url,
    categoryId: queryCondition.categoryId
  });
};

// 监听查询结果变化，同步当前页码
watch(() => queriedResult.current, (newCurrent) => {
  queryCondition.current = newCurrent;
});

const handleDelete = async (id) => {
  await ElMessageBox.confirm('确认删除该资源？','删除询问',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).catch(() =>{
    ElMessage.info('删除动作被取消')
    return new Promise (() =>{})
  })

  // 执行删除操作
 const {data} = await deleteResource(id)
 if(data.code === '000000'){
  ElMessage.success('删除资源成功')
  queryResources();
 } else {
  ElMessage.error('删除资源失败')
  throw new error('删除资源失败')
 }

}
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <el-form :inline="true" :model="formInline" ref="queryFm" class="demo-form-inline">
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="formInline.name" placeholder="资源名称" clearable />
        </el-form-item>
        <el-form-item label="资源路径" prop="url">
          <el-input v-model="formInline.url" placeholder="资源路径" clearable />
        </el-form-item>
        <el-form-item label="资源分类" prop="categoryId">
          <el-select v-model="formInline.categoryId" placeholder="资源分类" class="select">
            <el-option label="不限" value="" />
            <el-option 
              v-for="category in allResourceCategory"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery()">搜索查询</el-button>
          <el-button type="primary" @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <el-button size="large" @click="dlgCreateOrEdit?.initAndShow()">添加资源</el-button>
    <el-button size="large" @click="router.push({ name: 'resource-category' })">资源类别</el-button>
    <el-table :data="queriedResult.records" border style="width: 100%">
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column prop="name" label="资源名称" align="center" />
      <el-table-column prop="url" label="资源路径" align="center" />
      <el-table-column prop="description" label="描述" align="center" />
      <el-table-column prop="createdTime" label="添加时间" :formatter="timeFormatter" align="center" />
      <el-table-column label="操作" align="center" v-slot:default="{ row }">
        <el-button type="primary" @click="dlgCreateOrEdit?.initAndShow(row.id)">编辑</el-button>
        <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
      </el-table-column>
    </el-table>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryCondition.current"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="queryCondition.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="queriedResult.total"
    />

    <DlgResourceCreateOrEdit ref="dlgCreateOrEdit" />
  </el-card>
</template>

<style scoped>
.el-table {
  margin-top: 17px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.select {
  width: 150px;
}
</style>